<!DOCTYPE html>
<html>
<head>
    <title>图片上传测试</title>
    <style>
        body {
            font-family: Arial, sans-serif;
            max-width: 800px;
            margin: 0 auto;
            padding: 20px;
            background-color: #f5f5f5;
        }
        h1 {
            color: #333;
            text-align: center;
        }
        .upload-container {
            background-color: #fff;
            padding: 20px;
            border-radius: 8px;
            box-shadow: 0 2px 10px rgba(0, 0, 0, 0.1);
            margin-bottom: 20px;
        }
        .drop-area {
            border: 2px dashed #ccc;
            border-radius: 8px;
            padding: 40px;
            text-align: center;
            cursor: pointer;
            margin-bottom: 20px;
            transition: all 0.3s;
        }
        .drop-area:hover {
            border-color: #8a2be2;
            background-color: #f9f9f9;
        }
        .drop-area.highlight {
            border-color: #8a2be2;
            background-color: #f0f0f0;
        }
        .preview-container {
            display: flex;
            flex-wrap: wrap;
            gap: 10px;
            margin-top: 20px;
        }
        .preview-item {
            position: relative;
            width: 100px;
            height: 100px;
        }
        .preview-image {
            width: 100%;
            height: 100%;
            object-fit: cover;
            border-radius: 4px;
        }
        .remove-btn {
            position: absolute;
            top: 5px;
            right: 5px;
            background-color: rgba(0, 0, 0, 0.5);
            color: white;
            border: none;
            border-radius: 50%;
            width: 20px;
            height: 20px;
            cursor: pointer;
            display: flex;
            align-items: center;
            justify-content: center;
        }
        .button {
            background-color: #8a2be2;
            color: white;
            border: none;
            padding: 10px 20px;
            border-radius: 4px;
            cursor: pointer;
            font-size: 16px;
            transition: all 0.3s;
        }
        .button:hover {
            background-color: #7a1cd1;
        }
        .button:disabled {
            background-color: #ccc;
            cursor: not-allowed;
        }
        .result-container {
            background-color: #fff;
            padding: 20px;
            border-radius: 8px;
            box-shadow: 0 2px 10px rgba(0, 0, 0, 0.1);
            margin-top: 20px;
        }
        .result-title {
            font-weight: bold;
            margin-bottom: 10px;
        }
        .result-content {
            background-color: #f5f5f5;
            padding: 10px;
            border-radius: 4px;
            font-family: monospace;
            white-space: pre-wrap;
            overflow-x: auto;
        }
        .image-test-container {
            margin-top: 20px;
        }
        .image-test-title {
            font-weight: bold;
            margin-bottom: 10px;
        }
        .image-test-content {
            display: flex;
            flex-direction: column;
            gap: 10px;
        }
    </style>
</head>
<body>
    <h1>图片上传测试</h1>
    
    <div class="upload-container">
        <h2>上传图片</h2>
        <div class="drop-area" id="drop-area">
            <p>点击或拖拽图片到此处上传</p>
            <input type="file" id="file-input" accept="image/*" style="display: none;" multiple>
        </div>
        
        <div class="preview-container" id="preview-container"></div>
        
        <button class="button" id="upload-btn" disabled>上传图片</button>
    </div>
    
    <div class="result-container" style="display: none;" id="result-container">
        <div class="result-title">上传结果：</div>
        <div class="result-content" id="result-content"></div>
        
        <div class="image-test-container">
            <div class="image-test-title">图片测试：</div>
            <div class="image-test-content" id="image-test-content"></div>
        </div>
    </div>
    
    <script>
        // 全局变量
        let uploadedImages = [];
        
        // 添加全局错误处理器
        window.onerror = function(message, source, lineno, colno, error) {
            console.error('全局错误:', message);
            console.error('错误来源:', source);
            console.error('行号:', lineno);
            console.error('列号:', colno);
            console.error('错误对象:', error);
            return false;
        };
        
        // 监听所有fetch请求
        const originalFetch = window.fetch;
        window.fetch = function(url, options) {
            console.log('发起请求:', url, options);
            return originalFetch(url, options)
                .then(response => {
                    console.log('请求完成:', url, response.status);
                    return response;
                })
                .catch(error => {
                    console.error('请求失败:', url, error);
                    throw error;
                });
        };
        
        // DOM元素
        const dropArea = document.getElementById('drop-area');
        const fileInput = document.getElementById('file-input');
        const previewContainer = document.getElementById('preview-container');
        const uploadBtn = document.getElementById('upload-btn');
        const resultContainer = document.getElementById('result-container');
        const resultContent = document.getElementById('result-content');
        const imageTestContent = document.getElementById('image-test-content');
        
        // 事件监听
        dropArea.addEventListener('click', () => fileInput.click());
        
        dropArea.addEventListener('dragover', (e) => {
            e.preventDefault();
            dropArea.classList.add('highlight');
        });
        
        dropArea.addEventListener('dragleave', () => {
            dropArea.classList.remove('highlight');
        });
        
        dropArea.addEventListener('drop', (e) => {
            e.preventDefault();
            dropArea.classList.remove('highlight');
            
            if (e.dataTransfer.files.length > 0) {
                handleFiles(e.dataTransfer.files);
            }
        });
        
        fileInput.addEventListener('change', () => {
            if (fileInput.files.length > 0) {
                handleFiles(fileInput.files);
            }
        });
        
        uploadBtn.addEventListener('click', uploadImages);
        
        // 处理文件
        function handleFiles(files) {
            for (let i = 0; i < files.length; i++) {
                const file = files[i];
                
                // 验证文件类型
                if (!file.type.match('image.*')) {
                    alert('请上传图片文件');
                    continue;
                }
                
                // 验证文件大小
                if (file.size > 5 * 1024 * 1024) {
                    alert('图片大小不能超过5MB');
                    continue;
                }
                
                const reader = new FileReader();
                reader.onload = function(e) {
                    const imageData = e.target.result;
                    
                    // 添加到预览
                    addImagePreview(imageData, file.name, file.type);
                    
                    // 存储图片数据
                    uploadedImages.push({
                        name: file.name,
                        data: imageData,
                        type: file.type
                    });
                    
                    // 启用上传按钮
                    uploadBtn.disabled = false;
                };
                reader.readAsDataURL(file);
            }
        }
        
        // 添加图片预览
        function addImagePreview(imageData, fileName, fileType) {
            const previewItem = document.createElement('div');
            previewItem.className = 'preview-item';
            
            const previewImage = document.createElement('img');
            previewImage.className = 'preview-image';
            previewImage.src = imageData;
            previewImage.alt = fileName;
            
            const removeButton = document.createElement('button');
            removeButton.className = 'remove-btn';
            removeButton.textContent = '×';
            removeButton.onclick = function(e) {
                e.stopPropagation();
                removeImage(imageData);
                previewContainer.removeChild(previewItem);
                
                // 如果没有图片，禁用上传按钮
                if (uploadedImages.length === 0) {
                    uploadBtn.disabled = true;
                }
            };
            
            previewItem.appendChild(previewImage);
            previewItem.appendChild(removeButton);
            previewContainer.appendChild(previewItem);
        }
        
        // 移除图片
        function removeImage(imageData) {
            const index = uploadedImages.findIndex(img => img.data === imageData);
            if (index !== -1) {
                uploadedImages.splice(index, 1);
            }
        }
        
        // 上传图片
        function uploadImages() {
            // 禁用上传按钮
            uploadBtn.disabled = true;
            uploadBtn.textContent = '上传中...';
            
            // 创建测试帖子
            const postData = {
                title: '测试帖子',
                content: '这是一个测试帖子，用于测试图片上传功能。',
                tags: ['测试', '图片上传'],
                images: uploadedImages
            };
            
            // 发送请求
            fetch('/api/forum/posts-with-tags', {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json'
                },
                body: JSON.stringify(postData)
            })
            .then(response => {
                if (!response.ok) {
                    throw new Error(`上传失败，状态码：${response.status}`);
                }
                return response.json();
            })
            .then(data => {
                // 显示结果
                resultContainer.style.display = 'block';
                resultContent.textContent = JSON.stringify(data, null, 2);
                
                // 测试图片访问
                testImages(data.id);
                
                // 重置上传按钮
                uploadBtn.textContent = '上传成功';
                setTimeout(() => {
                    uploadBtn.textContent = '上传图片';
                    uploadBtn.disabled = false;
                }, 2000);
                
                // 清空预览和已上传图片
                previewContainer.innerHTML = '';
                uploadedImages = [];
            })
            .catch(error => {
                console.error('上传失败:', error);
                
                // 显示错误信息
                resultContainer.style.display = 'block';
                resultContent.textContent = `上传失败：${error.message}`;
                
                // 重置上传按钮
                uploadBtn.textContent = '上传失败';
                setTimeout(() => {
                    uploadBtn.textContent = '重新上传';
                    uploadBtn.disabled = false;
                }, 2000);
            });
        }
        
        // 测试图片访问
        function testImages(postId) {
            // 获取帖子详情
            fetch(`/api/forum/posts/${postId}`)
                .then(response => {
                    if (!response.ok) {
                        throw new Error(`获取帖子失败，状态码：${response.status}`);
                    }
                    return response.json();
                })
                .then(post => {
                    if (!post.images || post.images.length === 0) {
                        imageTestContent.textContent = '帖子没有图片';
                        return;
                    }
                    
                    // 清空测试内容
                    imageTestContent.innerHTML = '';
                    
                    // 添加每张图片的测试
                    post.images.forEach((image, index) => {
                        // 确保image对象存在
                        if (!image) {
                            console.error(`图片 ${index + 1} 对象为空`);
                            return;
                        }
                        
                        const imageTest = document.createElement('div');
                        imageTest.style.marginBottom = '20px';
                        
                        // 图片信息
                        const imageInfo = document.createElement('div');
                        imageInfo.style.marginBottom = '10px';
                        imageInfo.innerHTML = `
                            <div>图片 ${index + 1}：</div>
                            <div>ID: ${image.id || '未知'}</div>
                            <div>路径: ${image.image_path || '未知'}</div>
                        `;
                        
                        // 图片测试
                        const imageElement = document.createElement('img');
                        imageElement.src = image.image_path || '/static/uploads/default-image-error.jpg';
                        imageElement.alt = `图片 ${index + 1}`;
                        imageElement.style.maxWidth = '300px';
                        imageElement.style.maxHeight = '300px';
                        imageElement.style.border = '1px solid #ccc';
                        imageElement.style.borderRadius = '4px';
                        
                        // 图片加载状态
                        const imageStatus = document.createElement('div');
                        imageStatus.textContent = '图片加载中...';
                        imageStatus.style.marginTop = '5px';
                        
                        // 图片加载事件
                        imageElement.onload = function() {
                            imageStatus.textContent = '图片加载成功';
                            imageStatus.style.color = 'green';
                        };
                        imageElement.onerror = function() {
                            imageStatus.textContent = '图片加载失败';
                            imageStatus.style.color = 'red';
                            
                            // 尝试修复路径
                            setTimeout(() => {
                                let fixedPath = image.image_path || '';
                                if (fixedPath && !fixedPath.startsWith('http://') && !fixedPath.startsWith('https://') && !fixedPath.startsWith('/static/')) {
                                    if (fixedPath.startsWith('/uploads/')) {
                                        fixedPath = '/static' + fixedPath;
                                        imageElement.src = fixedPath;
                                        imageStatus.textContent = '尝试修复路径: ' + fixedPath;
                                    }
                                }
                            }, 1000);
                        };
                        
                        // 添加到测试内容
                        imageTest.appendChild(imageInfo);
                        imageTest.appendChild(imageElement);
                        imageTest.appendChild(imageStatus);
                        imageTestContent.appendChild(imageTest);
                    });
                })
                .catch(error => {
                    console.error('获取帖子失败:', error);
                    imageTestContent.textContent = `获取帖子失败：${error.message}`;
                });
        }
    </script>
</body>
</html> 